package com.da.web.sys_menu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.da.common.Result;
import com.da.web.sys_menu.entity.SysMenu;
import com.da.web.sys_menu.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author da
 * @time 2023/12/1 下午 4:27
 */
@RestController
@RequestMapping("/api/menu")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;

    //新增
    @PostMapping
    public Result addMenu(@RequestBody SysMenu menu) {
        menu.setCreateTime(new Date());
        boolean save = sysMenuService.save(menu);
        if (save) {
            return Result.success("新增成功!");
        }
        return Result.error("新增失败!");
    }

    //编辑
    @PutMapping
    public Result editMenu(@RequestBody SysMenu menu) {
        menu.setUpdateTime(new Date());
        boolean save = sysMenuService.updateById(menu);
        if (save) {
            return Result.success("编辑成功!");
        }
        return Result.error("编辑失败!");
    }

    //删除
    @DeleteMapping("/{menuId}")
    public Result deleteMenu(@PathVariable("menuId") Long menuId) {
        QueryWrapper<SysMenu> query = new QueryWrapper<>();
        //如果有下级，不能删除
        query.lambda().eq(SysMenu::getParentId, menuId);
        List<SysMenu> list = sysMenuService.list(query);
        if (!list.isEmpty()) {
            return Result.error("该菜单存在下级,不能删除!");
        }
        boolean save = sysMenuService.removeById(menuId);
        if (save) {
            return Result.success("删除成功!");
        }
        return Result.error("删除失败!");
    }

    //菜单列表
    @GetMapping("/list")
    public Result getList() {
        List<SysMenu> list = sysMenuService.getList();
        return Result.success("查询成功", list);
    }

    //上级菜单列表
    @GetMapping("/parent")
    public Result getParentList() {
        List<SysMenu> list = sysMenuService.getParentList();
        return Result.success("查询成功", list);
    }

}
